package com.itheima.project.filter;

import com.itheima.project.constant.SuperConstant;
import com.itheima.project.utils.EmptyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName TenantFilter.java
 * @Description 多租户过滤器
 */
@Slf4j
@Component
@Order(-99)
public class TenantGlobalFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //放入下游请求头中
        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().build();

        //获取请求头JWT中信息
        String userToken = exchange.getRequest().getHeaders().getFirst(SuperConstant.USER_TOKEN);
        //已登录从头部中拿到userToken
        if (!EmptyUtil.isNullOrEmpty(userToken)){
            serverHttpRequest = serverHttpRequest.mutate().header(SuperConstant.USER_TOKEN, userToken).build();
        }

        //获得请求头中的store信息
        String storeToken = exchange.getRequest().getHeaders().getFirst(SuperConstant.STORE_TOKEN);
        //已登录从头部中拿到storeToken
        if (!EmptyUtil.isNullOrEmpty(storeToken)){
            //放入下游请求头中
            serverHttpRequest = serverHttpRequest.mutate().header(SuperConstant.STORE_TOKEN,storeToken).build();
        }

        //获得请求头中的是否开启 租户隔离字段
        String enableTenant = exchange.getRequest().getHeaders().getFirst(SuperConstant.ENABLE_TENANT);
        if (!EmptyUtil.isNullOrEmpty(enableTenant)){
            //放入下游请求头中
            serverHttpRequest = serverHttpRequest.mutate().header(SuperConstant.ENABLE_TENANT,enableTenant).build();
        }

        //把新的 exchange放回到过滤链
        return chain.filter(exchange.mutate().request(serverHttpRequest).build());
    }
}
